package com.homework.news

import android.content.Context
import android.media.Image
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.MediaController
import android.widget.TextView
import android.widget.VideoView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlin.random.Random

class VideoAdapter(val videos: List<Video>): RecyclerView.Adapter<VideoAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
        val author: TextView = view.findViewById(R.id.author)
        val title: TextView = view.findViewById(R.id.title)
        val imageView: ImageView = view.findViewById(R.id.imageView)
        val hotValue: TextView = view.findViewById(R.id.hotValue)
        val playCount: TextView = view.findViewById(R.id.playCount)
    }

    private var mOnItemClickListener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.video_item, parent, false)

        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        println("开始生成视频")
        val video = videos[position]
        holder.author.text = video.author
        holder.title.text = video.title
        Glide.with(holder.imageView.context).load(video.item_cover).into(holder.imageView)
        if (video.hot_value == 0){
            video.hot_value = 10346925 + Random.nextInt(0, 6562468)
            video.play_count = 10346925 + Random.nextInt(0, 6562468)
        }
        holder.hotValue.text = video.hot_value.toString()
        holder.playCount.text = video.play_count.toString()

        if(mOnItemClickListener!=null){
            println("执行点击数事件")
            var position = holder.layoutPosition
            holder.title.setOnClickListener {
                mOnItemClickListener!!.onItemClick(holder.title, position)
            }
        }
    }

    override fun getItemCount(): Int {
        return videos.size
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.mOnItemClickListener = onItemClickListener
    }

}